package vip.xiaonuo.smzq.modular.nbfb.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.io.resource.ClassPathResource;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.WriteSheet;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import vip.xiaonuo.common.excel.CommonExcelCustomMergeStrategy;
import vip.xiaonuo.common.util.CommonResponseUtil;
import vip.xiaonuo.smzq.core.tools.excel.DynamicTitleWriteHandler;
import vip.xiaonuo.smzq.core.tools.excel.ExcelExporter;
import vip.xiaonuo.smzq.core.tools.file.PathUtils;
import vip.xiaonuo.smzq.core.utils.StringUtilTool;
import vip.xiaonuo.smzq.modular.deom.TypeProcessing;
import vip.xiaonuo.smzq.modular.dictionary.entity.Cb13Zycllx;
import vip.xiaonuo.smzq.modular.dictionary.mapper.Cb13ZycllxMapper;
import vip.xiaonuo.smzq.modular.kcl.entity.Zycl;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbFiveVo;
import vip.xiaonuo.smzq.modular.nbfb.entity.vo.NbfbThreeVo;
import vip.xiaonuo.smzq.modular.nbfb.mapper.ZyclFiveMapper;
import vip.xiaonuo.smzq.modular.nbfb.service.INbfbFiveService;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class NbfbFiveServiceImpl extends ServiceImpl<ZyclFiveMapper, Zycl> implements INbfbFiveService {
    @Resource
    private ZyclFiveMapper zyclFiveMapper;
    @Resource
    private Cb13ZycllxMapper cb13ZycllxMapper;

    @Value("${file.base}")
    String baseFilePath;


    /**
     * 年报附表5
     * SQQ
     *
     * @param nd   年度
     * @param kcdm 节点_矿产代码_统计对象
     * @return
     */

    @Override
    public List<NbfbFiveVo> getNbfbFive(Integer nd, String kcdm) {
        String[] array = {"42201", "42202", "32006", "63701"};
        List<NbfbFiveVo> list = new ArrayList<>();

        Integer kcdmStr=null;
        Integer tjdx=null;

        try {
            String sql = " and";
//            if (nd != null) {
//                sql += " ks.nd=" + nd + " and";
//            }
            if (kcdm != null && !kcdm.equals("undefined")) {
               //判断是否是特殊矿种
                String tskcdm = StringUtilTool.extractMiddlePart(kcdm);
                if (Arrays.toString(array).contains(tskcdm)) {
//                    sql += " zy.kcdm='" + tskcdm + "' and";
                    kcdmStr= Integer.valueOf(tskcdm);
                } else {
                    List<Integer> kzbhList = TypeProcessing.strToList(kcdm);
                    if (kzbhList != null && kzbhList.size() == 3) {
                        kcdmStr= kzbhList.get(1);
                        tjdx=kzbhList.get(2);
//                        sql += " zy.kcdm='" + kzbhList.get(1) + "' and zy.tjdx=" + kzbhList.get(2) + " and";

                    }
                }
            }
//            sql = sql.replaceFirst(" and$", "");
//            list = zyclFiveMapper.getNbfbFive(sql);
            list = zyclFiveMapper.getNbfbFive(nd, kcdmStr,tjdx);

        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }

    /**
     * 导出年报附表5
     * SQQ
     *
     * @param nd   年度
     * @param kcdm 节点_矿产代码_统计对象
     * @return
     */
    @Override
    public void exportNbfbFive(Integer nd, String kcdm, HttpServletResponse response) {
////        File tempFile = null;
//        try {
//
//            List<NbfbFiveVo> list = getNbfbFive(nd, kcdm);
////            String fileName = nd + "年报报表附表5.xlsx";
////            tempFile = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + fileName);
//
//            String dynamicTitle = "截至"+(nd-1)+"年底保有资源量"; // 动态标题
//            String sheetName=nd + "年报报表附表5";
//
////            EasyExcel.write(tempFile.getPath(), NbfbFiveVo.class)
////                    .sheet(nd + "年报报表附表5")
////                    .doWrite(list);
////            IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(tempFile));
//            //CommonDownloadUtil.download(tempFile, response);
//
//            ExcelExporter. exportNbfbFile(list,dynamicTitle,sheetName,response);
//
//
//        } catch (Exception e) {
//            log.error(nd + "年报报表附表5：", e);
//            try {
//                CommonResponseUtil.renderError(response, nd + "年报报表附表5");
//            } catch (IOException ioException) {
//                ioException.printStackTrace();
//            }
//        } finally {
////            FileUtil.del(tempFile);
//        }

        exportNbfbFiveTemplateExport(nd, kcdm, response);
    }

    /**
     * 根据模版导出年报附表5
     *
     * @param nd
     * @param kcdm
     * @param response
     * @author Sqq
     */
    public void exportNbfbFiveTemplateExport(Integer nd, String kcdm, HttpServletResponse response) {
        //年报附表5模板路径
        String templateFilePath = PathUtils.getNbfbPath(5);
        // 加载模板文件
        ClassPathResource classPathResource = new ClassPathResource(templateFilePath);
        InputStream inputStream = classPathResource.getStream();
        File tempFile = null;
        try {

            List<NbfbFiveVo> list = getNbfbFive(nd, kcdm);
            String fileName = nd + "年报报表附表5.xlsx";
            tempFile = new File(PathUtils.getUpLoadPath(baseFilePath) + File.separator + fileName);
            // 写excel
            try (ExcelWriter excelWriter = EasyExcel.write(tempFile.getPath())
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(list.stream().map(NbfbFiveVo::getNum)
                            .collect(Collectors.toList()), 0))
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(list.stream().map(NbfbFiveVo::getKcmc)
                            .collect(Collectors.toList()), 1))
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(list.stream().map(NbfbFiveVo::getKcmc)
                            .collect(Collectors.toList()), 2))
                    .registerWriteHandler(new CommonExcelCustomMergeStrategy(list.stream().map(NbfbFiveVo::getKcdsl)
                            .collect(Collectors.toList()), 3))
                    .withTemplate(inputStream).build()
            ) {
                WriteSheet writeSheet = EasyExcel.writerSheet().build();
                // 使用 fill 方法填充数据
                excelWriter.fill(list, writeSheet);
                Map<String, Object> map = new HashMap<>();
                map.put("nd", nd);
                map.put("lastNd", nd - 1);
                excelWriter.fill(map, writeSheet);
            }
            // 将生成的文件发送给客户端
            IoUtil.write(response.getOutputStream(), true, FileUtil.readBytes(tempFile));
        } catch (Exception e) {
            log.error(nd + "年报报表附表5：", e);
            try {
                CommonResponseUtil.renderError(response, nd + "年报报表附表5");
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
        } finally {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            FileUtil.del(tempFile);
        }


    }


}
